package easy;

import java.util.Stack;

public class ValidParentheses {
    public boolean isValid0(String s) {
        String temp = "";
        int count = 0;
        int length = s.length();
        for (int i = 0; i < length; i++) {
            char c = s.charAt(i);
            if (c == '(' || c == '[' || c == '{') {
                temp += c;
                count++;
            } else {
                int tempLength = temp.length();
                if(tempLength != 0){
                    char lastC = temp.charAt(tempLength-1);
                    if (c == ')' && lastC == '(') {
                        temp = temp.substring(0, tempLength-1);
                        count++;
                    } else if (c == ']' && lastC == '[') {
                        temp = temp.substring(0, tempLength-1);
                        count++;
                    } else if (c == '}' && lastC == '{') {
                        temp = temp.substring(0, tempLength-1);
                        count++;
                    } else {
                        break;
                    }
                }else{
                    break;
                }
            }
        }
        if(temp.equals("") && count==s.length()){
            return true;
        }else{
            return false;
        }
    }

    public boolean isValid(String s) {
        Stack<Character> stack = new Stack<Character>();
        for(char c:s.toCharArray()){
            if(c == '('){
                stack.push(')');
            }else if(c =='['){
                stack.push(']');
            }else if(c =='{'){
                stack.push('}');
            }else{
                if(stack.isEmpty() || stack.pop()!=c){
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}
